package com.easyse.easysesecurity.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.easyse.model.DO.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    // 用来接收用户信息
    private User user;
    private List<String> permissions;
    // 这个成员变量redis不会序列化存储它 不需要序列化存储
    // 使用注解：
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorityList;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }


    /**
     * 此方法用于获取该用户的权限
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把permissions中的权限信息封装成 SimpleGrantedAuthority 对象
        /*
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
            authorityList.add(simpleGrantedAuthority);
        }
        */
        // 函数式编写
        if(authorityList!=null){
            return authorityList;
        }
        authorityList = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorityList;
    }

    @Override
    public String getPassword() {

        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
